import { log } from 'console';
import { LogMessage } from './LogType.d';
import fs from 'fs';
import path from 'path';

const LOGS_DIR = path.join(process.cwd(), 'logs');
const MAX_LOG_SIZE = 300; // 300字节
let logStream: fs.WriteStream | null = null;
let currentLogPath = '';
let logStartTime = '';

// 确保日志目录存在
function ensureLogsDirectory() {
  if (!fs.existsSync(LOGS_DIR)) {
    fs.mkdirSync(LOGS_DIR, { recursive: true });
  }
}

// 生成日志文件名
function generateLogFileName(): string {
  const now = new Date();
  return `application_${now.getFullYear()}${pad(now.getMonth()+1)}${pad(now.getDate())}-` +
         `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}.log`;
}

// 补零
function pad(num: number): string {
  return num.toString().padStart(2, '0');
}

// 检查日志文件大小并在需要时循环
function checkLogSizeAndRotate() {
  if (!logStream || !currentLogPath) return;
  
  try {
    const stats = fs.statSync(currentLogPath);
    if (stats.size >= MAX_LOG_SIZE) {
      // 关闭当前日志流
      logStream.end();
      logStream = null;
      
      // 创建新日志文件
      const newLogFileName = generateLogFileName();
      const newLogPath = path.join(LOGS_DIR, newLogFileName);
      
      logStartTime = new Date().toISOString();
      logStream = fs.createWriteStream(newLogPath, { flags: 'a' });
      currentLogPath = newLogPath;
      logStream.write(`${logStartTime}--- Logging started (rotated) ---\n`);
    }
  } catch (error) {
    console.error('Error checking log size:', error);
  }
}

// 处理来自主进程的消息
process.on('message', (msg: { 
  command: string; 
  log?: LogMessage 
}) => {
  switch (msg.command) {
    case 'start':
      try {
        ensureLogsDirectory();
        const logFileName = generateLogFileName();
        currentLogPath = path.join(LOGS_DIR, logFileName);
        logStartTime = new Date().toISOString();
        logStream = fs.createWriteStream(currentLogPath, { flags: 'a' });
        logStream.write(`${logStartTime}--- Logging started ---\n`);
        if (msg.log) {
          logStream.write(`${new Date().toISOString()} [START] ${JSON.stringify(msg.log)}\n`);
        }
        process.send?.({ success: true });
      } catch (error) {
        process.send?.({ success: false, errors: (error as Error).message });
      }
      break;
      
    case 'log':
      if (logStream && msg.log) {
        // 检查日志文件大小并在需要时循环
        checkLogSizeAndRotate();
        
        const { level, timestamp, ip = '', logger, extra } = msg.log;
        console.log(timestamp);
        const times = timestamp.replace(/T/, ' ').replace(/(\d{2}:\d{2}:\d{2}).(\d{3})Z/, '$1.$2');
        let logEntry = `${times} [${level}-LOG] ${ip} ${logger}`;
        
        if (level === 'VERBOSE' && extra) {
          logEntry += ` | ${JSON.stringify(extra, null, 2)}`;
        } else if (level === 'ERROR' && msg.log.stack) {
          logEntry += `\n    Stack: ${msg.log.stack}`;
        } else if(level === 'ERROR' && extra){
          logEntry += ` | ${JSON.stringify(extra, null, 2)}`; 
        }
        
        logStream.write(logEntry + '\n');
      }
      break;
      
    case 'stop':
      if (logStream) {
        console.log(msg.command);
        logStream.write('--- Logging stopped ---\n');
        logStream.end();
        logStream = null;
        currentLogPath = '';
      }
      process.send?.({ success: true });
      break;
  }
});

process.on('exit', () => {
  logStream?.end();
});

process.on('SIGTERM', () => {
  logStream?.end();
  process.exit(0);
});